from tool_class.db_connection import DatabaseOperations


class RuleProcessingBase:

    def __init__(self,conn):
        self.conn = conn

    def get_resource_group(self, resource_id):
        sql =f""" SELECT
                        c.NAME 
                    FROM
                        ins_data_resource b
                        INNER JOIN ins_data_resource_desc c ON b.id = resource_id 
                    WHERE
                        b.id = '{resource_id}' 
                        AND c.status = "Enabled"
                """
        # print(sql)
        results = self.conn.execute_query(sql)
        strings = [itme["NAME"] for itme in results]
        result = "(" + ",".join(f'"{s}"' for s in strings) + ")"
        # print(result,"result")
        # print(results)
        #返回一个字符串，格式为(a,b,c)
        return result
    def get_regulation_list(self,regulation_id = None):
        #所需要的字段
        fields_to_keep = {'name','process_phase','regulation_weight','create_time','regulation_id',"field_name","matching_rule","channel",
                          "regulation_type",'variable_value','logical_operator','condition_type','condition_detail','detail_type',"variable_value"}
        sql = f"""SELECT
                    * 
                FROM
                    ins_regulation_info
                    INNER JOIN ins_regulation_detail ON ins_regulation_info.id = ins_regulation_detail.regulation_id 
                WHERE
                    ins_regulation_info.del_flag = '0' 
                    AND ins_regulation_detail.del_flag = '0' 
                    AND ins_regulation_info.id = "0bd4ef2cfc162d31332e979bad2bd3e2"
              """
        original_list = self.conn.execute_query(sql)
        regulation_dict = {}
        # print(original_list,"original_dict")
        # 将每条规则过滤字段掉不需要的字段,列表为规则详情存储
        for item in original_list:
            new_dict = {key: value for key, value in item.items() if key in fields_to_keep}
            if new_dict['regulation_id'] not in regulation_dict:
                regulation_dict[new_dict['regulation_id']] = [new_dict]
                continue
            regulation_dict[new_dict['regulation_id']].append(new_dict)
        # print("regulation_dict--->",regulation_dict,)
        regulation_list = []
        for key in regulation_dict:
            regulation = {
                "regulation_id": key,
                "process_phase": regulation_dict[key][0]['process_phase'],
                "regulation_type": regulation_dict[key][0]['regulation_type'],
                "create_time":regulation_dict[key][0]['create_time'],
                "regulation_weight": regulation_dict[key][0]['regulation_weight'],
                "channel": regulation_dict[key][0]['channel'],
                "detail_list": regulation_dict[key]
            }
            regulation_list.append(regulation)
        return regulation_list

    def join_condition(self, condition):
        # print("condition", condition)
        parts = []
        for item in condition:
            temp = self.join_field_detail(**item)
            if temp:
                parts.append(f" {item['matching_rule']} {temp}")
        where_item = ''.join(parts)
        where_condition = where_item.replace(" and ", "", 1) if "and" in where_item else where_item.replace(" or ", "", 1)
        # print(where_condition,"----where_condition")
        return where_condition

    def join_field_detail(self,**kwargs):
        if kwargs['variable_value'] == "textLength":
            #处理文本长度，返回CHAR_LENGTH(字段名)，并且去掉单引号
            condition_detail = self.join_logical_operator(kwargs['logical_operator'],kwargs['condition_type'],kwargs['condition_detail']).replace("'","")
            return f"CHAR_LENGTH({kwargs['field_name']}) {condition_detail}"
        return f"{kwargs['field_name']} {self.join_logical_operator(kwargs['logical_operator'],kwargs['condition_type'],kwargs['condition_detail'])}"

    def join_condition_type(self, condition_type,condition_detail):
        condition = {
            "value": condition_detail,
            "resourceGroup": self.get_resource_group(condition_detail) if condition_type == "resourceGroup" else None,
            "regex": condition_detail ,
        }
        # print(condition[condition_type],"condition[condition_type]")
        return condition[condition_type]

    "正则遇到为空数据时 还未处理 此处记录下"
    def join_logical_operator(self, logical_operator,condition_type = None,condition_detail = None):
        symbol = {
            "empty": "is null",
            "notEmpty": "is not null",
            "contain": "REGEXP",
            "notContain": "NOT REGEXP",
            "equals": "=" if condition_type == "value" else ("in" if condition_type == "resourceGroup" else f"REGEXP '^{condition_detail}$'"),
            "notEquals": "!=" if condition_type == "value" else ("not in" if condition_type == "resourceGroup" else f"NOT REGEXP '^{condition_detail}$'"),
            "greaterThan": ">",
            "lessThan": "<",
            "greaterThanOrEqual": ">=",
            "lessThanOrEqual": "<="
        }
        #如果是==某个正则表达式时返回REGEXP ^{condition_detail}$
        if condition_type == "regex" and (logical_operator == "equals" or logical_operator == "notEquals"):
            return symbol[logical_operator]
        #如果是资源组且包含或不包含时返回
        elif condition_type == "resourceGroup" and (logical_operator == "contain" or logical_operator == "notEquals"):
            resource_group= self.get_resource_group(condition_detail).replace("(","").replace(")","").replace('"',"")
            # print(resource_group,"resource_group")
            join_resource_group = "|".join(resource_group.split(","))
            # print(join_resource_group,"join_resource_group")
            return f"REGEXP '{join_resource_group}'" if logical_operator == "contain" else f"NOT REGEXP '{join_resource_group}'"
        #为空和不为空时不需要条件详情
        elif not condition_type:
            return symbol[logical_operator]
        else:
            join_condition = f"{symbol[logical_operator]} '{self.join_condition_type(condition_type, condition_detail)}'"
            return join_condition

    def get_resource(self):
        name = self.get_resource_group("9b52b878f2c63c4cb6a9cb9f7a542193")
        print(name,"name")
        sql = f""" select * from ins_data_resource_desc where name in {name}  """
        results = self.conn.execute_query(sql)
        print("results---->",results)


if __name__ == '__main__':
    conn = DatabaseOperations()
    conn.connect("富通东方", "mysql_query")
    rule_obj = RuleProcessingBase(conn)
    # print(rule_obj.join_logical_operator("LessThanOrEqual","value","9b52b878f2c63c4cb6a9cb9f7a542193"))
    print(rule_obj.get_regulation_list())
    # for i in rule_obj.get_regulation_list()['b53b07399550b3c054ee87e00984a008']:
    # rule_obj.join_condition(rule_obj.get_regulation_list())

    # rule_obj.get_resource()
    # result = rule_obj.get_resource_group("9b52b878f2c63c4cb6a9cb9f7a542193")
    # print(result,"123")
    # rule_obj.join_condition_type("value","123")

